import 'package:flutter/material.dart';
import 'package:x3_base_package/x3_base_package.dart';
import 'package:x3_business_core/business_customer/ful_components/business_customer_details_edit_label_tab_form.dart';

class BusinessCustomerDetailsTagEdit extends StatefulWidget {
  static String sName = 'BusinessCustomerDetailsTagEdit';

  @override
  _BusinessCustomerDetailsTagEditState createState() => _BusinessCustomerDetailsTagEditState();
}

class _BusinessCustomerDetailsTagEditState extends State<BusinessCustomerDetailsTagEdit> implements BaseCatalogResponse {
  Map<String, dynamic> _dataSource;
  String _vipId;

  //是否更改标签(删除或添加)
  bool _changedTags = false;
  List<BaseTabConfig> _baseTabConfig = [];
  BaseTabBarPage _baseTabBarPage;
  // final List<String> _tagsAlias = ['基础资料', '会员形象', '消费行为', '价值诉求'];
  // final List<String> _tags = ['重要信息', '性格喜好', '联系信息', '外貌信息'];
  final List<String> _tagsAlias = ['首购', '复购', '三次购'];
  final List<String> _tags = ['重要信息', '性格喜好', '联系信息'];

  @override
  Widget build(BuildContext context) {
    dynamic arguments = BaseRouterUtil.getArguments(context);
    _vipId = BaseUtils.getKeyData(arguments, 'vipId').toString();
    return BaseScaffoldComponent(
      willPopScope: _onPop,
      title: '添加标签',
      child: BaseScreenRefreshComponent(
        request: new BaseScreenRequestModel('/x3-service-vip-bills-center/vipbills/vipuserbills/vipclerk/data/tag', params: {'vipId': _vipId}),
        builder: _buildScaffoldWidget,
      ),
    );
  }

  Widget _buildScaffoldWidget(BaseHttpResultModel requestResult) {
    return BaseScreenRefreshComponent(
      request: BaseScreenRequestModel('/x3-service-vip-bills-center/vipbills/vipuserbills/vipclerk/get/tag/{vipid}', method: BaseHttpMethodEnum.GET, params: {'vipid': _vipId}),
      builder: (BaseHttpResultModel vipResult) => _buildContent(vipResult, requestResult), //requestResult:全部标签  vipResult：已选标签
    );
  }

  Widget _buildContent(BaseHttpResultModel vipResult, BaseHttpResultModel requestResult) {
    _dataCollation(vipResult, requestResult);
    //数据整理
    return Column(
      children: [
        _baseTabBarPage.buildTabBar(context),
        Expanded(child: _baseTabBarPage.buildTabView()),
      ],
    );
  }

  void _dataCollation(BaseHttpResultModel vipResult, BaseHttpResultModel requestResult) {
    this._initDataSource(vipResult);
    List<dynamic> requestResultList = requestResult.data['response'];

    ///整理数据
    List<Widget> _buildComponent = BaseCatalogController.catalogResponseComponents(requestResult, this.catalog());
    _baseTabConfig.clear();
    _tags.asMap().keys.forEach((index) {
      int _componentIndex = requestResultList.indexWhere((element) {
        String _alias = "";
        if (element is Map && element.containsKey('name')) {
          _alias = element['name'];
        }
        return _alias == _tags[index];
      });
      if (_componentIndex != -1) _baseTabConfig.add(BaseTabConfig(text: _tagsAlias[index], child: _buildComponent[_componentIndex]));
    });
    _baseTabBarPage = BaseTabBarPage(_baseTabConfig);
  }

  /// 返回
  Future<bool> _onPop() async {
    BaseRouterUtil().pop(_changedTags);
    return Future.value(false);
  }

  @override
  Map<String, Widget Function(BaseHttpResponseModel response, dynamic dataSource)> catalog() {
    return {
      'MainBusinessContent': (BaseHttpResponseModel response, dynamic dataSource) => BusinessCustomerDetailsEditLabelTabForm(response: response, dataSource: dataSource, formDataSource: _dataSource, showTitle: false, isScroll: true),
    };
  }

  /// 获取默认参数
  void _initDataSource(BaseHttpResultModel vipResult) {
    if (this._dataSource != null) return;
    dynamic arguments = BaseRouterUtil.getArguments(context);
    String vipId = BaseUtils.getKeyData(arguments, 'vipId').toString();
    List<dynamic> datas = vipResult.data ?? [];
    Map<String, dynamic> dataSource = {'vipId': vipId};

    datas.forEach((data) {
      String propertyId = BaseUtils.getKeyData(data, 'propertyId').toString();
      String value = BaseUtils.getKeyData(data, 'value').toString();
      String valueText = BaseUtils.getKeyData(data, 'valueText').toString();
      bool isMultiple = value.contains(',');

      /// 多选
      if (isMultiple == true) {
        List _val = value.split(',');
        List _valText = valueText.split(',');
        List<Map<String, dynamic>> _data = [];
        for (int i = 0; i < _val.length; i++) {
          _data.add({'key': _val[i], 'value': _valText[i]});
        }
        dataSource.addAll({propertyId: _data});
      } else {
        // 单选
        dataSource.addAll({
          propertyId: {'key': value, 'value': valueText}
        });
      }
    });
    this._dataSource = dataSource;
  }
}
